package cn.virens.common.project.base.utils.enums;

import cn.virens.common.mybatis.entity.BaseEnum;
import cn.virens.common.util.core.stream.StreamUtil;
import cn.virens.common.util.exception.APIException;
import cn.virens.common.util.exception.ExceptionUtil;
import org.dromara.hutool.core.reflect.ClassUtil;

import java.util.stream.Stream;

public class EnumUtil {
    /**
     * 获取枚举名称
     */
    public static String name(Class<? extends BaseEnum<?>> clazz) throws Exception {
        return ClassUtil.getClassName(clazz, true);
    }

    /**
     * 获取枚举名称
     */
    public static String safeName(Class<? extends BaseEnum<?>> clazz) throws APIException {
        return ExceptionUtil.safe1(() -> name(clazz));
    }

    /**
     * 调用枚举的values方法获取全部值
     */
    public static BaseEnum<?>[] values(Class<? extends BaseEnum<?>> clazz) throws Exception {
        return (BaseEnum<?>[]) clazz.getMethod("values").invoke(null);
    }

    /**
     * 调用枚举的values方法获取全部值
     */
    public static BaseEnum<?>[] safeValues(Class<? extends BaseEnum<?>> clazz) throws APIException {
        return ExceptionUtil.safe1(() -> values(clazz));
    }

    /**
     * 扫描有效的枚举类
     */
    public static Stream<Class<BaseEnum<?>>> scanPackage(String... pkgs) {
        return StreamUtil.stream(pkgs).flatMap(packagePath -> {
            return ClassUtil.scanPackage(packagePath).stream();
        }).map(a -> to(a)).filter(a -> a != null);
    }

    @SuppressWarnings("unchecked")
    private static Class<BaseEnum<?>> to(Class<?> clazz) {
        if (BaseEnum.class.isAssignableFrom(clazz)) {
            return (Class<BaseEnum<?>>) clazz;
        } else {
            return null;
        }
    }
}
